package com.ssy.lingxi.product.serviceImpl.es;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.constant.product.CommodityStatusEnum;
import com.ssy.lingxi.common.constant.product.UnitPriceStrategyApplyTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.MemberLrcCacheDTO;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.utils.DateUtil;
import com.ssy.lingxi.component.redis.service.IRedisUtils;
import com.ssy.lingxi.product.api.model.request.CommodityCreditScore;
import com.ssy.lingxi.product.api.model.request.CommoditySold;
import com.ssy.lingxi.product.api.model.request.channelCommodity.ChannelCommodityQueryRequest;
import com.ssy.lingxi.product.api.model.request.commodity.CommodityQueryRequest;
import com.ssy.lingxi.product.api.model.response.SimpleBrandResponse;
import com.ssy.lingxi.product.api.model.response.channelCommodity.ChannelCommodityESResponse;
import com.ssy.lingxi.product.api.model.response.channelCommodity.ChannelCommodityMemberESResponse;
import com.ssy.lingxi.product.api.model.response.commodity.*;
import com.ssy.lingxi.product.entity.OftenBuyCommodity;
import com.ssy.lingxi.product.entity.OrderCommodity;
import com.ssy.lingxi.product.entity.OrderCommoditySold;
import com.ssy.lingxi.product.entity.channelCommodity.ChannelCommodity;
import com.ssy.lingxi.product.entity.commodity.Commodity;
import com.ssy.lingxi.product.entity.commodity.CommodityUnitPriceAndPic;
import com.ssy.lingxi.product.entity.es.*;
import com.ssy.lingxi.product.entity.es.channel.EsChannelCommodityMember;
import com.ssy.lingxi.product.repository.OftenBuyCommodityRepository;
import com.ssy.lingxi.product.repository.OrderCommoditySoldRepository;
import com.ssy.lingxi.product.repository.commodity.CommodityUnitPriceAndPicRepository;
import com.ssy.lingxi.product.repository.es.EsCommodityRepository;
import com.ssy.lingxi.product.service.IChannelCommodityService;
import com.ssy.lingxi.product.service.ICommodityService;
import com.ssy.lingxi.product.service.es.ISyncEsCommodityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * 同步商品实现类
 *
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/8/1
 */
@Service
public class SyncEsCommodityServiceImpl implements ISyncEsCommodityService {

    @Resource
    private EsCommodityRepository esCommodityRepository;

    @Resource
    private OrderCommoditySoldRepository orderCommoditySoldRepository;

    @Resource
    private OftenBuyCommodityRepository oftenBuyCommodityRepository;

    @Resource
    private CommodityUnitPriceAndPicRepository commodityUnitPriceAndPicRepository;

    @Resource
    private ICommodityService commodityService;

    @Resource
    private IChannelCommodityService channelCommodityService;

    @Resource
    private IRedisUtils redisUtils;

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    //每次分页同步的数量
    private final int pageSize = 2000;

    /**
     * 同步商品信息
     */
    @Override
    public String syncCommodity() {
        log.info("同步商品信息开始");
        long startTime = System.currentTimeMillis();
        //先清除数据
        esCommodityRepository.deleteAll();

        int current = 1;
        boolean isContinue = true;
        int commodityCount = 0;

        //将数据库中的商品已售数据更新到es中
        List<OrderCommodity> orderCommodityList = orderCommoditySoldRepository.findByType(1);
        Map<Long, OrderCommodity> orderCommodityMap = orderCommodityList.stream().collect(Collectors.toMap(OrderCommodity::getCommodityId, OrderCommodity -> OrderCommodity));

        while (isContinue) {
            PageVO pageVO = new PageVO();
            pageVO.setCurrent(current);
            pageVO.setPageSize(pageSize);
            CommodityQueryRequest commodityQueryRequest = new CommodityQueryRequest();
            List<Integer> statusList = new ArrayList<>();
            statusList.add(CommodityStatusEnum.On_Shelf.getCode());
            commodityQueryRequest.setStatusList(statusList);
            Page<Commodity> result = commodityService.getCommodityList(pageVO, commodityQueryRequest);
            if (result != null) {
                List<Commodity> commodityList = result.getContent();
                if (!commodityList.isEmpty()) {
                    //查询商品对应的店铺积分
                    List<String> keyList = commodityList.stream().map(commodityDetailResponse -> {
                        Long memberId = commodityDetailResponse.getMemberId();
                        Long memberRoleId = commodityDetailResponse.getMemberRoleId();
                        return Constants.MEMBER_LRC_PREFIX + Constants.MEMBER_LRC_SPLIT + memberId + Constants.MEMBER_LRC_SPLIT + memberRoleId;
                    }).distinct().collect(Collectors.toList());
                    HashMap<String, Integer> memberLrcMap = new HashMap<>();
                    for (int i = 0; i < keyList.size(); i++) {
                        memberLrcMap.put(keyList.get(i), i);
                    }
                    List<Object> memberLrcList = redisUtils.getBatch(keyList, Constants.REDIS_USER_INDEX);
                    //这里需要转换一下，不然数据多的话会出现栈溢出
                    List<CommodityDetailResponse> commodityDetailResponseList = commodityList.stream().map(commodity -> BeanUtil.copyProperties(commodity, CommodityDetailResponse.class)).collect(Collectors.toList());
                    List<EsCommodity> resultList = commodityDetailResponseList.stream().map(commodity -> {
                        EsCommodity esCommodity = new EsCommodity();
                        //不同属性名的映射
                        CopyOptions copyOptions = new CopyOptions();
                        Map<String, String> map = new HashMap<>();
                        map.put("unitPriceAndPicList", "unitPricePicList");
                        copyOptions.setFieldMapping(map);
                        BeanUtil.copyProperties(commodity, esCommodity, copyOptions);

                        //获取商品已售数量
                        if (orderCommodityMap.size() > 0) {
                            Long commodityId = commodity.getId();
                            OrderCommodity orderCommodity = orderCommodityMap.get(commodityId);
                            if (orderCommodity != null) {
                                List<OrderCommoditySold> orderCommoditySoldList = orderCommodity.getOrderCommoditySoldList();
                                if (orderCommoditySoldList != null && orderCommoditySoldList.size() > 0) {
                                    List<EsCommoditySoldCount> commoditySoldCountList = orderCommoditySoldList.stream().map(orderCommoditySold -> BeanUtil.copyProperties(orderCommoditySold, EsCommoditySoldCount.class)).collect(Collectors.toList());
                                    esCommodity.setCommoditySoldCountList(commoditySoldCountList);
                                }
                            }
                        }

                        //店铺积分
                        Long memberId = esCommodity.getMemberId();
                        Long memberRoleId = esCommodity.getMemberRoleId();
                        String mapKey = Constants.MEMBER_LRC_PREFIX + Constants.MEMBER_LRC_SPLIT + memberId + Constants.MEMBER_LRC_SPLIT + memberRoleId;
                        Integer index = memberLrcMap.get(mapKey);
                        if (index != null) {
                            Object obj = memberLrcList.get(index);
                            if (obj != null) {
                                MemberLrcCacheDTO memberLrcCacheDTO = (MemberLrcCacheDTO) obj;
                                Integer creditPoint = memberLrcCacheDTO.getCreditPoint();
                                if (creditPoint != null && creditPoint > 0) {
                                    esCommodity.setCreditScore(creditPoint);
                                }
                            }
                        }

                        //去掉价格策略为false
                        List<EsUnitPriceStrategy> unitPriceStrategyList = esCommodity.getUnitPriceStrategyList().stream().filter(EsUnitPriceStrategy::getIsEnable).collect(Collectors.toList());
                        esCommodity.setIsUnitPriceStrategy(unitPriceStrategyList.size() > 0);
                        esCommodity.setUnitPriceStrategyList(unitPriceStrategyList);
                        String[] tags = {esCommodity.getName()};
//                        esCommodity.setTagsName(new Completion(tags));
                        return esCommodity;
                    }).collect(Collectors.toList());
                    if (resultList.size() > 0) {
                        commodityCount += resultList.size();
                        esCommodityRepository.saveAll(resultList);
                        log.info("已经同步完成" + resultList.size() + "条");
                    }
                    //判断是否最后一页
                    if (commodityList.size() != pageSize) {
                        isContinue = false;
                    } else {
                        current++;
                    }
                } else {
                    isContinue = false;
                }
            } else {
                isContinue = false;
            }
        }
        long endTime = System.currentTimeMillis();

        log.info("商品同步完成,商品总条数为：" + commodityCount + ",总耗时：" + DateUtil.getDiffTime(startTime, endTime));
        return "初始化成功";
    }

    /**
     * 同步渠道商品信息
     */
    @Override
    public String syncChannelCommodity() {
        log.info("渠道商品同步开始");

        long startTime = System.currentTimeMillis();

        int current = 1;
        boolean isContinue = true;

        //将数据库中的渠道商品已售数据更新到es中
        List<OrderCommodity> orderChannelCommodityList = orderCommoditySoldRepository.findByType(2);
        Map<Long, OrderCommodity> orderCommodityMap = orderChannelCommodityList.stream().collect(Collectors.toMap(OrderCommodity::getCommodityId, OrderCommodity -> OrderCommodity));

        while (isContinue) {
            PageVO pageVO = new PageVO();
            pageVO.setCurrent(current);
            pageVO.setPageSize(pageSize);
            ChannelCommodityQueryRequest commodityQueryRequest = new ChannelCommodityQueryRequest();
            Page<ChannelCommodity> result = channelCommodityService.getChannelCommodityList(pageVO, commodityQueryRequest);
            if (result != null) {
                List<ChannelCommodity> channelCommodityList = result.getContent();
                if (!channelCommodityList.isEmpty()) {
                    //这里需要转换一下，不然数据多的话会出现栈溢出
                    List<ChannelCommodityESResponse> channelCommodityESResponseList = channelCommodityList.stream().map(channelCommodity -> BeanUtil.copyProperties(channelCommodity, ChannelCommodityESResponse.class)).collect(Collectors.toList());
                    List<Long> channelCommodityIdList = new ArrayList<>();
                    Set<String> keySet = new HashSet<>();       //定义set可以防止重复
                    //遍历渠道商品，获取数据
                    channelCommodityESResponseList.forEach(channelCommodity -> {
                        channelCommodityIdList.add(channelCommodity.getCommodity().getId());
                        Long memberId = channelCommodity.getMemberId();
                        Long memberRoleId = channelCommodity.getMemberRoleId();
                        keySet.add(Constants.MEMBER_LRC_PREFIX + Constants.MEMBER_LRC_SPLIT + memberId + Constants.MEMBER_LRC_SPLIT + memberRoleId);
                    });
                    //一次性缓存商品信息，避免循环多次查询
                    List<EsCommodity> esCommodityList = esCommodityRepository.findByIdIn(channelCommodityIdList);
                    Map<Long, EsCommodity> esCommodityMap = esCommodityList.stream().collect(Collectors.toMap(EsCommodity::getId, EsCommodity -> EsCommodity));
                    //一次性缓存店铺积分，避免循环多次查询
                    List<String> keyList = new ArrayList<>(keySet);
                    HashMap<String, Integer> memberLrcMap = new HashMap<>();
                    for (int i = 0; i < keyList.size(); i++) {
                        memberLrcMap.put(keyList.get(i), i);
                    }
                    List<Object> memberLrcList = redisUtils.getBatch(keyList, Constants.REDIS_USER_INDEX);

                    //渠道商品信息封装到商品中
                    HashMap<Long, EsCommodity> map = new HashMap<>();
                    channelCommodityESResponseList.forEach(channelCommodity -> {
                        Long commodityId = channelCommodity.getCommodity().getId();
                        EsCommodity esCommodity = esCommodityMap.get(commodityId);
                        //如果商品不存在需要重新写入(只是预防商品被删，正常情况下不会出现为空)
                        if (esCommodity == null) {
                            Commodity commodity = commodityService.getCommodity(commodityId);
                            if (commodity != null) {
                                //这里需要转换一下，不然数据多的话会出现栈溢出
                                CommodityDetailResponse commodityDetailResponse = BeanUtil.copyProperties(commodity, CommodityDetailResponse.class);
                                esCommodity = new EsCommodity();
                                //不同属性名的映射
                                CopyOptions copyOptions = new CopyOptions();
                                Map<String, String> fieldMapping = new HashMap<>();
                                fieldMapping.put("unitPriceAndPicList", "unitPricePicList");
                                copyOptions.setFieldMapping(fieldMapping);
                                BeanUtil.copyProperties(commodityDetailResponse, esCommodity, copyOptions);

                                //查询会员商品已售数量
                                List<OrderCommodity> orderCommodityList = orderCommoditySoldRepository.findByCommodityIdAndType(esCommodity.getId(), 1);
                                if (orderCommodityList != null && orderCommodityList.size() > 0) {
                                    OrderCommodity orderCommodity = orderCommodityList.get(0);
                                    List<OrderCommoditySold> orderCommoditySoldList = orderCommodity.getOrderCommoditySoldList();
                                    if (orderCommoditySoldList != null && orderCommoditySoldList.size() > 0) {
                                        List<EsCommoditySoldCount> commoditySoldCountList = orderCommoditySoldList.stream().map(orderCommoditySold -> BeanUtil.copyProperties(orderCommoditySold, EsCommoditySoldCount.class)).collect(Collectors.toList());
                                        esCommodity.setCommoditySoldCountList(commoditySoldCountList);
                                    }
                                }
                            }
                        }
                        //设置商品来源和上级渠道id
                        List<ChannelCommodityMemberESResponse> memberList = channelCommodity.getMemberList();
                        if (memberList != null && !memberList.isEmpty()) {
                            EsCommodity finalCommodity = esCommodity;
                            memberList.forEach(memberResponse -> {
                                EsChannelCommodityMember esChannelCommodityMember = new EsChannelCommodityMember();
                                //不同属性名的映射
                                CopyOptions copyOptions = new CopyOptions();
                                Map<String, String> fieldMapping = new HashMap<>();
                                fieldMapping.put("unitPriceAndPicList", "unitPricePicList");
                                copyOptions.setFieldMapping(fieldMapping);
                                BeanUtil.copyProperties(memberResponse, esChannelCommodityMember, copyOptions);
                                esChannelCommodityMember.setChannelCommodityId(channelCommodity.getId());
                                esChannelCommodityMember.setChannelCommodityMemberId(esChannelCommodityMember.getId());
                                esChannelCommodityMember.setSource(channelCommodity.getSource());
                                esChannelCommodityMember.setChannelMemberId(channelCommodity.getMemberId());
                                esChannelCommodityMember.setChannelMemberName(channelCommodity.getMemberName());
                                esChannelCommodityMember.setChannelMemberRoleId(channelCommodity.getMemberRoleId());
                                esChannelCommodityMember.setChannelMemberRoleName(channelCommodity.getMemberRoleName());

                                //获取商品已售数量
                                if (orderCommodityMap.size() > 0) {
                                    Long channelCommodityId = memberResponse.getId();
                                    OrderCommodity orderCommodity = orderCommodityMap.get(channelCommodityId);
                                    if (orderCommodity != null) {
                                        List<OrderCommoditySold> orderCommoditySoldList = orderCommodity.getOrderCommoditySoldList();
                                        if (orderCommoditySoldList != null && orderCommoditySoldList.size() > 0) {
                                            List<EsCommoditySoldCount> commoditySoldCountList = orderCommoditySoldList.stream().map(orderCommoditySold -> BeanUtil.copyProperties(orderCommoditySold, EsCommoditySoldCount.class)).collect(Collectors.toList());
                                            esChannelCommodityMember.setCommoditySoldCountList(commoditySoldCountList);
                                        }
                                    }
                                }

                                //店铺积分
                                Long memberId = channelCommodity.getMemberId();
                                Long memberRoleId = channelCommodity.getMemberRoleId();
                                String mapKey = Constants.MEMBER_LRC_PREFIX + Constants.MEMBER_LRC_SPLIT + memberId + Constants.MEMBER_LRC_SPLIT + memberRoleId;
                                Integer index = memberLrcMap.get(mapKey);
                                if (index != null) {
                                    Object obj = memberLrcList.get(index);
                                    if (obj != null) {
                                        MemberLrcCacheDTO memberLrcCacheDTO = (MemberLrcCacheDTO) obj;
                                        Integer creditPoint = memberLrcCacheDTO.getCreditPoint();
                                        if (creditPoint != null && creditPoint > 0) {
                                            esChannelCommodityMember.setCreditScore(creditPoint);
                                        }
                                    }
                                }

                                Integer status = esChannelCommodityMember.getStatus();
                                if (CommodityStatusEnum.On_Shelf.getCode().equals(status)) {
                                    //相同商品id，把渠道会员商品信息进行合并
                                    EsCommodity existEsCommodity = map.get(commodityId);
                                    if (existEsCommodity != null) {
                                        List<EsChannelCommodityMember> existMemberList = existEsCommodity.getMemberList();
                                        if (!existMemberList.contains(esChannelCommodityMember)) {
                                            existMemberList.add(esChannelCommodityMember);
                                        }
                                        existEsCommodity.setMemberList(existMemberList);
                                    } else {
                                        List<EsChannelCommodityMember> esChannelCommodityMemberList = new ArrayList<>();
                                        esChannelCommodityMemberList.add(esChannelCommodityMember);
                                        finalCommodity.setMemberList(esChannelCommodityMemberList);
                                        map.put(commodityId, finalCommodity);
                                    }
                                }
                            });
                        }
                    });
                    //批量保存
                    List<EsCommodity> list = new ArrayList<>(map.values());
                    if (!list.isEmpty()) {
                        esCommodityRepository.saveAll(list);
                    }
                    //判断是否最后一页
                    if (channelCommodityList.size() != pageSize) {
                        isContinue = false;
                    } else {
                        current++;
                    }
                } else {
                    isContinue = false;
                }
            } else {
                isContinue = false;
            }
        }
        long endTime = System.currentTimeMillis();
        log.info("渠道商品同步完成,总耗时：" + DateUtil.getDiffTime(startTime, endTime));
        return "初始化成功";
    }


    /**
     * 更新会员商品已售数量
     *
     * @param commoditySold ShopId + [SkuId + 数量]
     */
    @Override
    public Boolean updateCommoditySold(CommoditySold commoditySold) {
        Long shopId = commoditySold.getShopId();
        HashMap<Long, Double> commodityCountMap = commoditySold.getCommodityCountMap();
        List<Long> UnitPricePicIdList = new ArrayList<>(commodityCountMap.keySet());
        List<OrderCommodity> orderCommodityList = new ArrayList<>();
        List<EsCommodity> esCommodityList = esCommodityRepository.findByUnitPricePicListIdIn(UnitPricePicIdList);
        if (esCommodityList != null && esCommodityList.size() > 0) {
            //如果调用接口时，commodityCountMap的所有Value都确保没有Null或小于等于0的值，去掉下面这句
            commodityCountMap.entrySet().removeIf(e -> e.getValue() == null || e.getValue() <= 0);
            esCommodityList.forEach(esCommodity -> {
                Long commodityId = esCommodity.getId();
                //用来判断ES是否已经记录了商品已售数量
                AtomicBoolean isExistCommoditySoldCount = new AtomicBoolean(true);
                //同一个商品下的所有sku已售数量进行累加
                double soldCount = esCommodity.getUnitPricePicList().stream().mapToDouble(unitPrice -> commodityCountMap.getOrDefault(unitPrice.getId(), 0D)).sum();
                //更新es中已有的数据
                List<EsCommoditySoldCount> esCommoditySoldCountList = esCommodity.getCommoditySoldCountList();
                if (esCommoditySoldCountList != null && esCommoditySoldCountList.size() > 0) {
                    esCommoditySoldCountList.forEach(esCommoditySoldCount -> {
                        Long commodityShopId = esCommoditySoldCount.getShopId();
                        if (commodityShopId.longValue() == shopId.longValue()) {
                            esCommoditySoldCount.setSold(esCommoditySoldCount.getSold() + soldCount);
                            isExistCommoditySoldCount.set(false);
                        }
                    });
                } else {
                    esCommoditySoldCountList = new ArrayList<>();
                }
                //es不存在则新增
                if (isExistCommoditySoldCount.get()) {
                    EsCommoditySoldCount esCommoditySoldCount = new EsCommoditySoldCount();
                    esCommoditySoldCount.setShopId(shopId);
                    esCommoditySoldCount.setSold(soldCount);
                    esCommoditySoldCountList.add(esCommoditySoldCount);
                    esCommodity.setCommoditySoldCountList(esCommoditySoldCountList);
                }
                //更新到数据库中(持久化是为了重启服务后重新赋值)
                OrderCommodity orderCommodity;
                List<OrderCommodity> existOrderCommoditySoldList = orderCommoditySoldRepository.findByCommodityIdAndType(commodityId, 1);
                if (existOrderCommoditySoldList != null && existOrderCommoditySoldList.size() > 0) {
                    orderCommodity = existOrderCommoditySoldList.get(0);
                } else {
                    orderCommodity = new OrderCommodity();
                    orderCommodity.setCommodityId(commodityId);
                    orderCommodity.setType(1);
                }
                //用来判断数据库是否已经记录了商品已售数量
                AtomicBoolean isExistOrderCommoditySoldCount = new AtomicBoolean(true);
                List<OrderCommoditySold> orderCommoditySoldList = orderCommodity.getOrderCommoditySoldList();
                if (orderCommoditySoldList != null && orderCommoditySoldList.size() > 0) {
                    orderCommoditySoldList.forEach(orderCommoditySold -> {
                        Long orderCommoditySoldShopId = orderCommoditySold.getShopId();
                        if (orderCommoditySoldShopId.longValue() == shopId.longValue()) {
                            orderCommoditySold.setSold(orderCommoditySold.getSold() == null ? soldCount : orderCommoditySold.getSold() + soldCount);
                            isExistOrderCommoditySoldCount.set(false);
                        }
                    });
                } else {
                    orderCommoditySoldList = new ArrayList<>();
                }
                if (isExistOrderCommoditySoldCount.get()) {
                    OrderCommoditySold orderCommoditySold = new OrderCommoditySold();
                    orderCommoditySold.setSold(soldCount);
                    orderCommoditySold.setShopId(shopId);
                    orderCommoditySold.setCreateTime(System.currentTimeMillis());
                    orderCommoditySold.setOrderCommodity(orderCommodity);
                    orderCommoditySoldList.add(orderCommoditySold);
                }
                orderCommodity.setOrderCommoditySoldList(orderCommoditySoldList);
                orderCommodityList.add(orderCommodity);
            });
            esCommodityRepository.saveAll(esCommodityList);
            orderCommoditySoldRepository.saveAll(orderCommodityList);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 更新常购清单
     */
    @Override
    public Boolean updateOftenBuyCommodity(CommoditySold commoditySold) {
        //获取参数
        Long shopId = commoditySold.getShopId();
        Long memberId = commoditySold.getMemberId();
        Long memberRoleId = commoditySold.getMemberRoleId();
        HashMap<Long, Double> commodityMap = commoditySold.getCommodityCountMap();
        List<Long> commoditySkuIdList = new ArrayList<>(commodityMap.keySet());
        //查询商品sku信息
        List<CommodityUnitPriceAndPic> commodityUnitPriceAndPicList = commodityUnitPriceAndPicRepository.findByIdIn(commoditySkuIdList);
        Map<Long, CommodityUnitPriceAndPic> commodityUnitPriceAndPicMap = commodityUnitPriceAndPicList.stream().collect(Collectors.toMap(CommodityUnitPriceAndPic::getId, CommodityUnitPriceAndPic -> CommodityUnitPriceAndPic));
        //查询常购清单
        List<OftenBuyCommodity> existOftenBuyCommodityList = oftenBuyCommodityRepository.findByShopIdAndMemberIdAndMemberRoleIdAndCommoditySkuIdIn(shopId, memberId, memberRoleId, commoditySkuIdList);
        HashMap<Long, OftenBuyCommodity> oftenBuyCommodityHashMap = new HashMap<>();
        existOftenBuyCommodityList.forEach(oftenBuyCommodity -> {
            oftenBuyCommodityHashMap.put(oftenBuyCommodity.getCommoditySku().getId(), oftenBuyCommodity);
        });

        List<OftenBuyCommodity> oftenBuyCommodityList = new ArrayList<>();
        for (Map.Entry<Long, Double> entry : commodityMap.entrySet()) {
            Long key = entry.getKey();
            Double value = entry.getValue();
            OftenBuyCommodity oftenBuyCommodity = oftenBuyCommodityHashMap.get(key);
            if (oftenBuyCommodity != null) {
                oftenBuyCommodity.setBuyCount(oftenBuyCommodity.getBuyCount() + value);
            } else {
                oftenBuyCommodity = new OftenBuyCommodity();
                oftenBuyCommodity.setCommoditySku(commodityUnitPriceAndPicMap.get(key));
                oftenBuyCommodity.setShopId(shopId);
                oftenBuyCommodity.setBuyCount(value);
                oftenBuyCommodity.setMemberId(memberId);
                oftenBuyCommodity.setMemberName(commoditySold.getMemberName());
                oftenBuyCommodity.setMemberRoleId(memberRoleId);
                oftenBuyCommodity.setMemberRoleName(commoditySold.getMemberRoleName());
                oftenBuyCommodity.setCreateTime(System.currentTimeMillis());
            }
            oftenBuyCommodityList.add(oftenBuyCommodity);
        }

        if (oftenBuyCommodityList.size() > 0) {
            oftenBuyCommodityRepository.saveAll(oftenBuyCommodityList);
        }
        return true;
    }

    /**
     * 更新渠道商品已售数量
     *
     * @param commoditySold ShopId + [SkuId + 数量]
     */
    @Override
    public Boolean updateChannelCommoditySold(CommoditySold commoditySold) {
        Long shopId = commoditySold.getShopId();
        HashMap<Long, Double> commodityCountMap = commoditySold.getCommodityCountMap();
        List<Long> UnitPricePicIdList = new ArrayList<>(commodityCountMap.keySet());
        List<OrderCommodity> orderCommodityList = new ArrayList<>();
        List<EsCommodity> esCommodityList = esCommodityRepository.findByMemberListUnitPricePicListIdIn(UnitPricePicIdList);
        if (esCommodityList != null && esCommodityList.size() > 0) {
            //如果调用接口时，commodityCountMap的所有Value都确保没有Null或小于等于0的值，去掉下面这句
            commodityCountMap.entrySet().removeIf(e -> e.getValue() == null || e.getValue() <= 0);
            esCommodityList.forEach(esCommodity -> {
                //用来判断ES是否已经记录了商品已售数量
                AtomicBoolean isExistCommoditySoldCount = new AtomicBoolean(true);
                //同一个商品下的所有sku已售数量进行累加
                List<EsChannelCommodityMember> memberList = esCommodity.getMemberList();
                if (memberList != null && memberList.size() > 0) {
                    memberList.forEach(esChannelCommodityMember -> {
                        double soldCount = esChannelCommodityMember.getUnitPricePicList().stream().mapToDouble(unitPrice -> commodityCountMap.getOrDefault(unitPrice.getId(), 0D)).sum();
                        //更新es中已有的数据
                        List<EsCommoditySoldCount> esCommoditySoldCountList = esChannelCommodityMember.getCommoditySoldCountList();
                        if (esCommoditySoldCountList != null && esCommoditySoldCountList.size() > 0) {
                            esCommoditySoldCountList.forEach(esCommoditySoldCount -> {
                                Long commodityShopId = esCommoditySoldCount.getShopId();
                                if (commodityShopId.longValue() == shopId.longValue()) {
                                    esCommoditySoldCount.setSold(esCommoditySoldCount.getSold() + soldCount);
                                    isExistCommoditySoldCount.set(false);
                                }
                            });
                        } else {
                            esCommoditySoldCountList = new ArrayList<>();
                        }
                        //es不存在则新增
                        if (isExistCommoditySoldCount.get()) {
                            EsCommoditySoldCount esCommoditySoldCount = new EsCommoditySoldCount();
                            esCommoditySoldCount.setShopId(shopId);
                            esCommoditySoldCount.setSold(soldCount);
                            esCommoditySoldCountList.add(esCommoditySoldCount);
                            esChannelCommodityMember.setCommoditySoldCountList(esCommoditySoldCountList);
                        }
                        Long channelCommodityId = esChannelCommodityMember.getId();
                        //更新到数据库中(持久化是为了重启服务后重新赋值)
                        OrderCommodity orderCommodity;
                        List<OrderCommodity> existOrderCommoditySoldList = orderCommoditySoldRepository.findByCommodityIdAndType(channelCommodityId, 2);
                        if (existOrderCommoditySoldList != null && existOrderCommoditySoldList.size() > 0) {
                            orderCommodity = existOrderCommoditySoldList.get(0);
                        } else {
                            orderCommodity = new OrderCommodity();
                            orderCommodity.setCommodityId(channelCommodityId);
                            orderCommodity.setType(2);
                        }
                        //用来判断数据库是否已经记录了商品已售数量
                        AtomicBoolean isExistOrderCommoditySoldCount = new AtomicBoolean(true);
                        List<OrderCommoditySold> orderCommoditySoldList = orderCommodity.getOrderCommoditySoldList();
                        if (orderCommoditySoldList != null && orderCommoditySoldList.size() > 0) {
                            orderCommoditySoldList.forEach(orderCommoditySold -> {
                                Long orderCommoditySoldShopId = orderCommoditySold.getShopId();
                                if (orderCommoditySoldShopId.longValue() == shopId.longValue()) {
                                    orderCommoditySold.setSold(orderCommoditySold.getSold() == null ? soldCount : orderCommoditySold.getSold() + soldCount);
                                    isExistOrderCommoditySoldCount.set(false);
                                }
                            });
                        } else {
                            orderCommoditySoldList = new ArrayList<>();
                        }
                        if (isExistOrderCommoditySoldCount.get()) {
                            OrderCommoditySold orderCommoditySold = new OrderCommoditySold();
                            orderCommoditySold.setSold(soldCount);
                            orderCommoditySold.setShopId(shopId);
                            orderCommoditySold.setCreateTime(System.currentTimeMillis());
                            orderCommoditySold.setOrderCommodity(orderCommodity);
                            orderCommoditySoldList.add(orderCommoditySold);
                        }
                        orderCommodity.setOrderCommoditySoldList(orderCommoditySoldList);
                        orderCommodityList.add(orderCommodity);
                    });
                }
            });
            esCommodityRepository.saveAll(esCommodityList);
            orderCommoditySoldRepository.saveAll(orderCommodityList);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 更新商品对应的店铺积分
     *
     * @param commodityCreditScore
     * @return
     */
    @Override
    public Boolean updateCommodityCreditScore(CommodityCreditScore commodityCreditScore) {
        Long memberId = commodityCreditScore.getMemberId();
        Long memberRoleId = commodityCreditScore.getMemberRoleId();
        Integer creditScore = commodityCreditScore.getCreditScore();
        Boolean isChannelMember = commodityCreditScore.getIsChannelMember();
        List<EsCommodity> esCommodityList;
        if (isChannelMember != null && isChannelMember) {
            esCommodityList = esCommodityRepository.findByMemberListChannelMemberIdAndMemberListChannelMemberRoleId(memberId, memberRoleId);
            esCommodityList.forEach(esCommodity -> esCommodity.getMemberList().forEach(esChannelCommodityMember -> {
                Long channelMemberId = esChannelCommodityMember.getChannelMemberId();
                Long channelMemberRoleId = esChannelCommodityMember.getChannelMemberRoleId();
                if (channelMemberId.longValue() == memberId.longValue() && channelMemberRoleId.longValue() == memberRoleId.longValue()) {
                    esChannelCommodityMember.setCreditScore(esChannelCommodityMember.getCreditScore() + creditScore);
                }
            }));
        } else {
            esCommodityList = esCommodityRepository.findByMemberIdAndMemberRoleId(memberId, memberRoleId);
            esCommodityList.forEach(esCommodity -> esCommodity.setCreditScore(esCommodity.getCreditScore() + creditScore));
        }
        if (esCommodityList.size() > 0) {
            log.info("更新商品数据条数：" + esCommodityList.size());
            esCommodityRepository.saveAll(esCommodityList);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 修改商品品牌
     *
     * @return
     */
    @Override
    public Boolean updateCommodityBrand(SimpleBrandResponse brandResponse) {
        Long brandId = brandResponse.getId();
        String brandName = brandResponse.getName();
        String logoUrl = brandResponse.getLogoUrl();
        List<EsCommodity> esCommodityList = esCommodityRepository.findByBrandId(brandId);
        if (esCommodityList != null && !esCommodityList.isEmpty()) {
            esCommodityList.forEach(commodity -> {
                EsBrand brand = commodity.getBrand();
                brand.setId(brandId);
                brand.setLogoUrl(logoUrl);
                brand.setName(brandName);
            });
            esCommodityRepository.saveAll(esCommodityList);
        }
        return true;
    }

    /**
     * 修改商品价格
     *
     * @param commodityDetailResponse
     */
    @Override
    public Boolean updateCommodityPrice(CommodityDetailResponse commodityDetailResponse) {
        if (commodityDetailResponse != null) {
            Long commodityId = commodityDetailResponse.getId();
            EsCommodity esCommodity = esCommodityRepository.findById(commodityId).orElse(null);
            if (esCommodity != null) {
                List<UnitPriceAndPicResponse> unitPriceAndPicList = commodityDetailResponse.getUnitPriceAndPicList();
                List<EsCommodityUnitPricePic> resultList = unitPriceAndPicList.stream().map(unitPriceAndPicResponse -> {
                    EsCommodityUnitPricePic unitPricePic = new EsCommodityUnitPricePic();
                    BeanUtil.copyProperties(unitPriceAndPicResponse, unitPricePic);
                    return unitPricePic;
                }).collect(Collectors.toList());
                esCommodity.setUnitPricePicList(resultList);

                esCommodity.setMin(commodityDetailResponse.getMin());
                esCommodity.setMax(commodityDetailResponse.getMax());
            } else {
                esCommodity = new EsCommodity();
                //不同属性名的映射
                CopyOptions copyOptions = new CopyOptions();
                Map<String, String> map = new HashMap<>();
                map.put("unitPriceAndPicList", "unitPricePicList");
                copyOptions.setFieldMapping(map);
                BeanUtil.copyProperties(commodityDetailResponse, esCommodity, copyOptions);
            }
            esCommodityRepository.save(esCommodity);
            return true;
        }
        return false;
    }

    /**
     * 上架/下架商品信息
     *
     * @param commodityDetailResponse
     */
    @Override
    public Boolean publishCommodity(CommodityDetailResponse commodityDetailResponse) {
        if (commodityDetailResponse != null) {
            Long commodityId = commodityDetailResponse.getId();
            EsCommodity esCommodity = esCommodityRepository.findById(commodityId).orElse(null);
            if (esCommodity == null) {
                esCommodity = new EsCommodity();
                //新上架的商品需要设置店铺积分
                Long memberId = commodityDetailResponse.getMemberId();
                Long memberRoleId = commodityDetailResponse.getMemberRoleId();
                String mapKey = Constants.MEMBER_LRC_PREFIX + Constants.MEMBER_LRC_SPLIT + memberId + Constants.MEMBER_LRC_SPLIT + memberRoleId;
                Object obj = redisUtils.get(mapKey, Constants.REDIS_USER_INDEX);
                if (obj != null) {
                    MemberLrcCacheDTO memberLrcCacheDTO = (MemberLrcCacheDTO) obj;
                    Integer creditPoint = memberLrcCacheDTO.getCreditPoint();
                    if (creditPoint != null && creditPoint > 0) {
                        esCommodity.setCreditScore(creditPoint);
                    }
                }
            }
            //不同属性名的映射
            CopyOptions copyOptions = new CopyOptions();
            Map<String, String> map = new HashMap<>();
            map.put("unitPriceAndPicList", "unitPricePicList");
            copyOptions.setFieldMapping(map);
            BeanUtil.copyProperties(commodityDetailResponse, esCommodity, copyOptions);
            String[] tags = {esCommodity.getName()};
//            esCommodity.setTagsName(new Completion(tags));

            esCommodityRepository.save(esCommodity);
            return true;
        }
        return false;
    }

    /**
     * 批量上架/下架商品信息
     *
     * @param commodityDetailResponseList
     */
    @Override
    public Boolean publishCommodityBatch(List<CommodityDetailResponse> commodityDetailResponseList) {
        try {
            List<Long> commodityIdList = commodityDetailResponseList.stream().map(CommodityDetailResponse::getId).collect(Collectors.toList());
            List<EsCommodity> existEsCommodityList = esCommodityRepository.findByIdIn(commodityIdList);
            Map<Long, EsCommodity> esCommodityMap = existEsCommodityList.stream().collect(Collectors.toMap(EsCommodity::getId, EsCommodity -> EsCommodity));

            //查询商品对应的店铺积分
            List<String> keyList = commodityDetailResponseList.stream().map(commodityDetailResponse -> {
                Long memberId = commodityDetailResponse.getMemberId();
                Long memberRoleId = commodityDetailResponse.getMemberRoleId();
                return Constants.MEMBER_LRC_PREFIX + Constants.MEMBER_LRC_SPLIT + memberId + Constants.MEMBER_LRC_SPLIT + memberRoleId;
            }).distinct().collect(Collectors.toList());
            HashMap<String, Integer> memberLrcMap = new HashMap<>();
            for (int i = 0; i < keyList.size(); i++) {
                memberLrcMap.put(keyList.get(i), i);
            }
            List<Object> memberLrcList = redisUtils.getBatch(keyList, Constants.REDIS_USER_INDEX);

            List<EsCommodity> commodityList = commodityDetailResponseList.stream().map(commodityDetailResponse -> {
                Long commodityId = commodityDetailResponse.getId();
                EsCommodity esCommodity = esCommodityMap.get(commodityId);
                if (esCommodity == null) {
                    esCommodity = new EsCommodity();

                    //店铺积分
                    Long memberId = esCommodity.getMemberId();
                    Long memberRoleId = esCommodity.getMemberRoleId();
                    String mapKey = Constants.MEMBER_LRC_PREFIX + Constants.MEMBER_LRC_SPLIT + memberId + Constants.MEMBER_LRC_SPLIT + memberRoleId;
                    Integer index = memberLrcMap.get(mapKey);
                    if (index != null) {
                        Object obj = memberLrcList.get(index);
                        if (obj != null) {
                            MemberLrcCacheDTO memberLrcCacheDTO = (MemberLrcCacheDTO) obj;
                            Integer creditPoint = memberLrcCacheDTO.getCreditPoint();
                            if (creditPoint != null && creditPoint > 0) {
                                esCommodity.setCreditScore(creditPoint);
                            }
                        }
                    }
                }

                //不同属性名的映射
                CopyOptions copyOptions = new CopyOptions();
                Map<String, String> map = new HashMap<>();
                map.put("unitPriceAndPicList", "unitPricePicList");
                copyOptions.setFieldMapping(map);
                BeanUtil.copyProperties(commodityDetailResponse, esCommodity, copyOptions);
                String[] tags = {esCommodity.getName()};
//                esCommodity.setTagsName(new Completion(tags));

                return esCommodity;
            }).collect(Collectors.toList());

            //持久化
            if (commodityList.size() > 0) {
                esCommodityRepository.saveAll(commodityList);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 下架所有商品
     *
     * @return
     */
    @Override
    public Boolean offPublishAllCommodity(List<Long> idList) {
        List<EsCommodity> esCommodityList = esCommodityRepository.findByIdIn(idList);
        esCommodityList.forEach(esCommodity -> esCommodity.setCommodityShopList(null));
        esCommodityRepository.saveAll(esCommodityList);
        return true;
    }

    /**
     * 上架/下架渠道商品信息
     *
     * @param channelCommodityList
     */
    @Override
    public Boolean publishChannelCommodity(List<ChannelCommodityESResponse> channelCommodityList) {
        try {
            List<Long> commodityIdList = channelCommodityList.stream().map(channelCommodityESResponse -> channelCommodityESResponse.getCommodity().getId()).distinct().collect(Collectors.toList());
            List<EsCommodity> existEsCommodityList = esCommodityRepository.findByIdIn(commodityIdList);
            Map<Long, EsCommodity> esCommodityMap = existEsCommodityList.stream().collect(Collectors.toMap(EsCommodity::getId, EsCommodity -> EsCommodity));

            List<Commodity> existCommodityList = commodityService.getCommodityByIdList(commodityIdList);
            Map<Long, Commodity> commodityMap = existCommodityList.stream().collect(Collectors.toMap(Commodity::getId, Commodity -> Commodity));


            //查询商品对应的店铺积分
            List<String> keyList = channelCommodityList.stream().map(commodityDetailResponse -> {
                Long memberId = commodityDetailResponse.getMemberId();
                Long memberRoleId = commodityDetailResponse.getMemberRoleId();
                return Constants.MEMBER_LRC_PREFIX + Constants.MEMBER_LRC_SPLIT + memberId + Constants.MEMBER_LRC_SPLIT + memberRoleId;
            }).distinct().collect(Collectors.toList());
            HashMap<String, Integer> memberLrcMap = new HashMap<>();
            for (int i = 0; i < keyList.size(); i++) {
                memberLrcMap.put(keyList.get(i), i);
            }
            List<Object> memberLrcList = redisUtils.getBatch(keyList, Constants.REDIS_USER_INDEX);

            List<EsCommodity> commodityList = channelCommodityList.stream().map(channelCommodity -> {
                Long commodityId = channelCommodity.getCommodity().getId();
                Commodity commodity = commodityMap.get(commodityId);
                if (commodity != null) {
                    Integer status = commodity.getStatus();
                    CommodityDetailResponse commodityDetailResponse = BeanUtil.copyProperties(commodity, CommodityDetailResponse.class);
                    EsCommodity esCommodity = esCommodityMap.get(commodityId);
                    //如果商品不存在需要重新写入
                    if (esCommodity == null) {
                        esCommodity = new EsCommodity();
                        //不同属性名的映射
                        CopyOptions copyOptions = new CopyOptions();
                        Map<String, String> map = new HashMap<>();
                        map.put("unitPriceAndPicList", "unitPricePicList");
                        copyOptions.setFieldMapping(map);
                        BeanUtil.copyProperties(commodityDetailResponse, esCommodity, copyOptions);
                    } else {
                        //如果es中存在, 但是当前商品的状态为审核通过之后的，更新es中商品的数据
                        if (status >= CommodityStatusEnum.Pass.getCode()) {
                            //不同属性名的映射
                            CopyOptions copyOptions = new CopyOptions();
                            Map<String, String> map = new HashMap<>();
                            map.put("unitPriceAndPicList", "unitPricePicList");
                            copyOptions.setFieldMapping(map);
                            BeanUtil.copyProperties(commodityDetailResponse, esCommodity, copyOptions);
                        }
                    }
                    List<EsChannelCommodityMember> resultList = new ArrayList<>();
                    List<ChannelCommodityMemberESResponse> memberList = channelCommodity.getMemberList();
                    if (memberList != null && !memberList.isEmpty()) {
                        resultList = memberList.stream().map(memberResponse -> {
                            EsChannelCommodityMember channelCommodityMember = new EsChannelCommodityMember();
                            //不同属性名的映射
                            CopyOptions copyOptions = new CopyOptions();
                            Map<String, String> map = new HashMap<>();
                            map.put("unitPriceAndPicList", "unitPricePicList");
                            copyOptions.setFieldMapping(map);
                            BeanUtil.copyProperties(memberResponse, channelCommodityMember, copyOptions);
                            channelCommodityMember.setChannelCommodityId(channelCommodity.getId());
                            channelCommodityMember.setChannelCommodityMemberId(channelCommodityMember.getId());
                            channelCommodityMember.setSource(channelCommodity.getSource());
                            channelCommodityMember.setChannelMemberId(channelCommodity.getMemberId());
                            channelCommodityMember.setChannelMemberName(channelCommodity.getMemberName());
                            channelCommodityMember.setChannelMemberRoleId(channelCommodity.getMemberRoleId());
                            channelCommodityMember.setChannelMemberRoleName(channelCommodity.getMemberRoleName());

                            //店铺积分
                            Long memberId = channelCommodity.getMemberId();
                            Long memberRoleId = channelCommodity.getMemberRoleId();
                            String mapKey = Constants.MEMBER_LRC_PREFIX + Constants.MEMBER_LRC_SPLIT + memberId + Constants.MEMBER_LRC_SPLIT + memberRoleId;
                            Integer index = memberLrcMap.get(mapKey);
                            if (index != null) {
                                Object obj = memberLrcList.get(index);
                                if (obj != null) {
                                    MemberLrcCacheDTO memberLrcCacheDTO = (MemberLrcCacheDTO) obj;
                                    Integer creditPoint = memberLrcCacheDTO.getCreditPoint();
                                    if (creditPoint != null && creditPoint > 0) {
                                        channelCommodityMember.setCreditScore(creditPoint);
                                    }
                                }
                            }

                            return channelCommodityMember;
                        }).collect(Collectors.toList());
                    }

                    //保留其他渠道商品信息
                    List<EsChannelCommodityMember> channelCommodityMemberList = esCommodity.getMemberList();
                    if (channelCommodityMemberList != null && !channelCommodityMemberList.isEmpty()) {
                        List<EsChannelCommodityMember> existMemberList = channelCommodityMemberList.stream().filter(channelCommodityMember -> !channelCommodityMember.getChannelMemberId().equals(channelCommodity.getId())).collect(Collectors.toList());
                        if (!existMemberList.isEmpty()) {
                            //新数据
                            List<EsChannelCommodityMember> newMemberList = resultList;
                            List<Long> memberIdList = newMemberList.stream().map(EsChannelCommodityMember::getId).collect(Collectors.toList());
                            //已经存在的旧数据
                            existMemberList.forEach(channelCommodityMember -> {
                                Long existId = channelCommodityMember.getId();
                                if (!memberIdList.contains(existId)) {
                                    newMemberList.add(channelCommodityMember);
                                }
                            });
                            //过滤掉没有商城的数据
                            esCommodity.setMemberList(newMemberList.stream().filter(channelCommodityMember -> channelCommodityMember.getShopList() != null && channelCommodityMember.getShopList().size() > 0).collect(Collectors.toList()));
                        } else {
                            esCommodity.setMemberList(resultList);
                        }
                    } else {
                        esCommodity.setMemberList(resultList);
                    }
                    //保存
                    String[] tags = {esCommodity.getName()};
//                    esCommodity.setTagsName(new Completion(tags));

                    return esCommodity;
                } else {
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
                }
            }).collect(Collectors.toList());

            //持久化
            esCommodityRepository.saveAll(commodityList);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 下架所有渠道商品
     *
     * @return
     */
    @Override
    public Boolean offPublishAllChannelCommodity(List<Long> idList) {
        List<EsCommodity> esCommodityList = esCommodityRepository.findByMemberListIdIn(idList);
        esCommodityList.forEach(commodity -> {
            List<EsChannelCommodityMember> memberList = commodity.getMemberList();
            memberList.forEach(channelCommodityMember -> {
                if (idList.contains(channelCommodityMember.getId())) {
                    channelCommodityMember.setStatus(CommodityStatusEnum.Off_Shelf.getCode());
                    channelCommodityMember.setShopList(null);
                }
            });
        });
        esCommodityRepository.saveAll(esCommodityList);
        return true;
    }

    /**
     * 修改价格策略
     *
     * @return
     */
    @Override
    public Boolean updateUnitPriceStrategy(UnitPriceStrategyResponse unitPriceStrategyResponse) {
        //获取参数信息
        Long id = unitPriceStrategyResponse.getId();
        Boolean isEnable = unitPriceStrategyResponse.getIsEnable();
        Long commodityId = unitPriceStrategyResponse.getCommodity().getId();
        EsCommodity esCommodity = esCommodityRepository.findById(commodityId).orElse(null);
        //获取商品的当前价格策略
        if (esCommodity != null) {
            List<EsUnitPriceStrategy> unitPriceStrategyList = esCommodity.getUnitPriceStrategyList();
            if (unitPriceStrategyList != null && unitPriceStrategyList.size() > 0) {
                //判断商品中的价格策略包不包含新增的价格策略
                Set<Long> unitPriceStrategyIdSet = unitPriceStrategyList.stream().map(EsUnitPriceStrategy::getId).collect(Collectors.toSet());
                if (unitPriceStrategyIdSet.contains(id)) {
                    if (isEnable) {
                        unitPriceStrategyList.forEach(unitPriceStrategy -> {
                            //将es中该条价格策略替换成最新的
                            Long unitPriceStrategyId = unitPriceStrategy.getId();
                            if (unitPriceStrategyId.equals(id)) {
                                unitPriceStrategy.setId(unitPriceStrategyId);
                                unitPriceStrategy.setMax(unitPriceStrategyResponse.getMax());
                                unitPriceStrategy.setMin(unitPriceStrategyResponse.getMin());
                                unitPriceStrategy.setIsEnable(unitPriceStrategyResponse.getIsEnable());
                                unitPriceStrategy.setPriceType(unitPriceStrategyResponse.getPriceType());
                                unitPriceStrategy.setShopId(unitPriceStrategyResponse.getShopId());
                                unitPriceStrategy.setType(unitPriceStrategyResponse.getType());
                                unitPriceStrategy.setEnvironment(unitPriceStrategyResponse.getEnvironment());
                                //商品价格
                                List<MemberUnitPriceResponse> memberUnitPriceList = unitPriceStrategyResponse.getMemberUnitPriceList();
                                List<ESUnitPriceStrategyMember> commodityMemberUnitPriceList = memberUnitPriceList.stream().map(memberUnitPriceResponse -> BeanUtil.copyProperties(memberUnitPriceResponse, ESUnitPriceStrategyMember.class)).collect(Collectors.toList());
                                unitPriceStrategy.setMemberUnitPriceList(commodityMemberUnitPriceList);
                                //判断是适用会员还是适用会员等级
                                Integer applyType = unitPriceStrategy.getApplyType();
                                if(UnitPriceStrategyApplyTypeEnum.Member.getCode().equals(applyType)){
                                    //适用会员
                                    List<UnitPriceMemberResponse> commodityMemberList = unitPriceStrategyResponse.getCommodityMemberList();
                                    if (!CollectionUtils.isEmpty(commodityMemberList)) {
                                        Set<EsCommodityMember> commodityMemberSet = commodityMemberList.stream().map(unitPriceMemberResponse -> BeanUtil.copyProperties(unitPriceMemberResponse, EsCommodityMember.class)).collect(Collectors.toSet());
                                        unitPriceStrategy.setCommodityMemberList(commodityMemberSet);
                                    }
                                }else{
                                    //适用会员等级
                                    List<UnitPriceMemberLevelResponse> commodityMemberLevelList = unitPriceStrategyResponse.getCommodityMemberLevelList();
                                    if (!CollectionUtils.isEmpty(commodityMemberLevelList)) {
                                        Set<EsUnitPriceStrategyMemberLevel> commodityMemberLevelSet = commodityMemberLevelList.stream().map(unitPriceMemberLevelResponse -> BeanUtil.copyProperties(unitPriceMemberLevelResponse, EsUnitPriceStrategyMemberLevel.class)).collect(Collectors.toSet());
                                        unitPriceStrategy.setCommodityMemberLevelList(commodityMemberLevelSet);
                                    }
                                }
                            }
                        });
                    }

                    boolean flag = false;
                    //判断是否存在价格策略
                    if(!CollectionUtils.isEmpty(unitPriceStrategyList)){
                        flag = true;
                        //剔除设置为false的价格策略
                        unitPriceStrategyList = unitPriceStrategyList.stream().map(unitPriceStrategy -> {
                            if (!unitPriceStrategy.getId().equals(id)) {
                                return unitPriceStrategy;
                            } else {
                                return null;
                            }
                        }).filter(Objects::nonNull).collect(Collectors.toList());
                    }
                    esCommodity.setIsUnitPriceStrategy(flag);
                    esCommodity.setUnitPriceStrategyList(unitPriceStrategyList);
                    esCommodityRepository.save(esCommodity);
                } else {
                    //不包含并且为true,说明是新增的价格策略
                    if (isEnable) {
                        unitPriceStrategyList.add(BeanUtil.copyProperties(unitPriceStrategyResponse, EsUnitPriceStrategy.class));
                        esCommodity.setIsUnitPriceStrategy(true);
                        esCommodity.setUnitPriceStrategyList(unitPriceStrategyList);
                        esCommodityRepository.save(esCommodity);
                    }
                }
            } else {
                //新增的价格策略
                if (isEnable) {
                    unitPriceStrategyList = new ArrayList<>();
                    unitPriceStrategyList.add(BeanUtil.copyProperties(unitPriceStrategyResponse, EsUnitPriceStrategy.class));
                    esCommodity.setIsUnitPriceStrategy(true);
                    esCommodity.setUnitPriceStrategyList(unitPriceStrategyList);
                    esCommodityRepository.save(esCommodity);
                }
            }
            return true;
        }
        return false;
    }
}